﻿using LPY.LeHealth.Service;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using LPY.LeHealth.Model;
using LPY.LeHealth.DTO;
using NPOI.SS.UserModel;
using NPOI.HSSF.UserModel;
using System.Data;
using System.IO;
namespace LPY.LeHealth.WebSite.Controllers
{
    /// <summary>
    /// 管理员后台控制器
    /// </summary>
    public class AdminController : BaseController
    {
        private InstallService installService;
        private UserService userService;
        private HospitalService hospitalService;
        private PersonalizedService personalizedService;
        private PhysicalService physicalService;
        private HospitalAdminService hospitalAdminService;
        private QuestionService questionservice;
        private ClassifyTypeService classifyTypeService;
        public AdminController()
        {
            installService = new InstallService();
            userService = new UserService();
            hospitalService = new HospitalService();
            personalizedService = new PersonalizedService();
            physicalService = new PhysicalService();
            hospitalAdminService = new HospitalAdminService();
            questionservice = new QuestionService();
            classifyTypeService=new ClassifyTypeService();
        }

        /// <summary>
        /// 管理员首页（显示基础体检项目）
        /// </summary>
        /// <returns></returns>
        [Common.Admin]
        public ActionResult Index()
        {
            //ViewBag.physical = new List<PhysicalItem>();// physicalService.ShowPhysical();
            return View();
        }

        #region 登录

        [HttpGet]
        public ActionResult Login()
        {
            return View();
        }

        /// <summary>
        /// 管理员登录
        /// </summary>
        /// <param name="name">用户名</param>
        /// <param name="pwd">密码</param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult Login(string name,string pwd)
        {
            var usr= userService.AdminLogin(name, pwd);
            if(null!=usr)
            {
                Session[CommonService.AdminSessionName] = usr;
                return RedirectToAction("Index");
            }
            else
            {
                return Content("用户名或密码错误！");
            }
        }

        #endregion

        #region  医院管理

        /// <summary>
        /// 显示医院列表（分页）
        /// </summary>
        /// <returns></returns>
        public ActionResult Hospital(int pageIndex = 1)
        {
            var pageSize = 5;
            long totalSize = 0;
            var hospitals = hospitalService.GetHospitals(pageIndex, pageSize, out totalSize);

            ViewBag.TotalPage = (int)Math.Ceiling((double)totalSize / (double)pageSize);
            ViewBag.PageIndex = pageIndex;
            ViewBag.Hospitals = hospitals;
            ViewBag.PageSize = pageSize;

            return View();
        }

        public ActionResult AddHospital(Hospital hos)
        {
            try
            {
                hos.GradeId = int.Parse(Request["grade"]);
                var result = hospitalService.AddHospital(hos);

                if (result)
                {
                    return Json(new { Code = 1, Msg = "处理成功！" });
                }
                else
                {
                    return Json(new { Code = 0, Msg = "处理失败！" });
                }
            }
            catch (Exception ex)
            {
                return Json(new { Code = 0, Msg = ex.Message });
            }
        }
        [HttpPost]
        public ActionResult GetHospital(int id)
        {
            try
            {
                var hos = hospitalService.GetHospitalById(id);

                if (null!=hos)
                {
                    return Json(new { Code = 1,Data=hos, Msg = "处理成功！" });
                }
                else
                {
                    return Json(new { Code = 0, Msg = "处理失败！" });
                }
            }
            catch (Exception ex)
            {
                return Json(new { Code = 0, Msg = ex.Message });
            }
        }




        /// <summary>
        /// 显示医院下的产品（单项体检和体检套餐）
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ActionResult HospitalExamination(int id)
        {
            var personalized = personalizedService.ShowPersonalized(id);

            return View(personalized);
        }

        /// <summary>
        /// 查看医院管理员视图
        /// </summary>
        /// <returns></returns>
        public ActionResult GetHospitalAdmin()
        {
            return View();
        }

        /// <summary>
        /// 查看医院管理员信息
        /// </summary>
        /// <returns></returns>
        public ActionResult GetHosAdmin()
        {

            var hospitalAdmins = hospitalAdminService.GetHospitalAdmin();
            return Json(hospitalAdmins);
        }
        /// <summary>
        /// 管理问答视图
        /// </summary>
        /// <returns></returns>
        public ActionResult GetQueAdmin()
        {
            var questionservic = questionservice.GetQueShow();
            ViewBag.Data = questionservic;
            return View(questionservic.ToList());
        }
        /// <summary>
        /// 显示所有问答表的信息
        /// </summary>
        /// <returns></returns>
        public ActionResult GetQueShow()
        {
            var questionservic = questionservice.GetQueShow();
            ViewBag.Data = questionservic;
            return View(questionservic.ToList());
        }
        /// <summary>
        /// 根据ID显示问答表信息
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult GetIdShow(int id)
        {
            var GetId = questionservice.GetIdShow(id);
            if (null != GetId)
            {
                return Json(new { Code = 1, Data = GetId, Msg = "处理成功！" });
            }
            else
            {
                return Json(new { Code = 1, Msg = "处理失败！" });
            }

        }
        #endregion

        #region  体检项管理

        /// <summary>
        /// 体检项管理（首页）
        /// </summary>
        public ActionResult PhysicalItem(int pageIndex = 1)
        {
            var pageSize = 5;
            long totalSize = 0;
            var hospitals = physicalService.GetPhysicalItemList(pageIndex, pageSize, out totalSize);

            ViewBag.TotalPage = (int)Math.Ceiling((double)totalSize / (double)pageSize);
            ViewBag.PageIndex = pageIndex;
            ViewBag.Data = hospitals;
            ViewBag.PageSize = pageSize;

            return View();
        }

        /// <summary>
        /// 修改体检项目
        /// </summary>
        /// <param name="physical"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult EditPhysical(PhysicalItem physical)
        {
            bool result = physicalService.UpdatePhysicalItem(physical);
            if (result == true)
            {
                return Json(new { Code = 1, Msg = "处理成功！" });
            }
            else
            {
                return Json(new { Code = 1, Msg = "处理成功！" });
            }

        }
        /// <summary>
        /// 修改医院信息 
        /// </summary>
        /// <param name="hospital"></param>
        /// <returns></returns>
        [HttpPost]
        
        public ActionResult EditHostpital(Hospital hospital)
        {
            hospital.GradeId = Convert.ToInt32(Request["Grade"]);
            hospital.Detail = Request["Details"];
            bool result = hospitalService.UpdatePhysicalItem(hospital);
            if (result == true)
            {
                return Json(new { Code = 1, Msg = "处理成功！" });
            }
            else
            {
                return Json(new { Code = 1, Msg = "处理成功！" });
            }
        }
        /// <summary>
        /// 删除医院
        /// </summary>
        /// <returns></returns>
        public int DelDetails()
        {
            int id = int.Parse(Request["Id"]);

            if (hospitalService.DeletePhysicalItemById(id))
            {
                return 1;
            }
            else
            {
                return 0;
            }
        }

        /// <summary>
        /// 获取体检项目信息
        /// </summary>
        /// <param name="id">体检项目id</param>
        /// <returns>体检项目信息</returns>
        public ActionResult GetPhysical(int id)
        {
            var model = physicalService.GetPhysicalItemById(id);
            if(null!=model)
            {
                return Json(new { Code = 1, Data = model, Msg = "处理成功！" });
            }
            else
            {
                return Json(new { Code = 1, Msg = "处理失败！" });
            }
        }
        /// <summary>
        /// 回复添加
        /// </summary>
        /// <param name="r"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult AddReplyd(ReplyDTO r)
        {
            r.Rdate = DateTime.Now.ToString();
            
            
            if(classifyTypeService.AddReplyd(r)>0)
            {
                return Json(new { Code = 1, Msg = "处理成功！" });
            }
            else
            {
                return Json(new { Code = 0, Msg = "处理失败！" });
            }
        }


        /// <summary>
        /// 添加体检项目
        /// </summary>
        /// <param name="physical"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult AddPhysicalItem(PhysicalItem physical)
        {
            var result=false;
            result = physicalService.AddPhysicalItem(physical);
            
            if (result)
            {
                return Json(new { Code = 1, Msg = "处理成功！" });
            }
            else
            {
                return Json(new { Code = 0, Msg = "处理失败！" });
            }
        }

        /// <summary>
        /// 删除体检项目
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult PhysicalItemDelete(int id)
        {
            var result = physicalService.DeletePhysicalItemById(id);
            if (result)
            {
                return Json(new { Code = 1, Msg = "处理成功！" });
            }
            else
            {
                return Json(new { Code = 0, Msg = "处理失败！" });
            }
        }

        #endregion

        #region 体检套餐

        //单项体检
        public ActionResult PhysicalSingle(int pageIndex = 1)
        {
            var pageSize = 5;
            long totalSize = 0;
            //获取单项体检列表
            var models = physicalService.GetPhysicalSingle(pageIndex, pageSize, out totalSize);

            ViewBag.TotalPage = (int)Math.Ceiling((double)totalSize / (double)pageSize);
            ViewBag.PageIndex = pageIndex;
            ViewBag.Data = models;
            ViewBag.PageSize = pageSize;

            //获取医院列表
            var hos= hospitalService.GetAllHospitall();
            ViewBag.Hospitals = hos;

            //获取体检类型列表
            var combos= physicalService.GetAllComboType();
            ViewBag.Combos = combos;

            //获取体检项目列表
            var items= physicalService.GetAllPhysicalItem();
            ViewBag.Items = items;

            return View();
        }

        //体检套餐
        public ActionResult PhysicalCombo(int pageIndex = 1)
        {
            var pageSize = 5;
            long totalSize = 0;
            //获取体检列表
            var models = physicalService.GetPhysicalCombo(pageIndex, pageSize, out totalSize);

            ViewBag.TotalPage = (int)Math.Ceiling((double)totalSize / (double)pageSize);
            ViewBag.PageIndex = pageIndex;
            ViewBag.Data = models;
            ViewBag.PageSize = pageSize;

            //获取医院列表
            var hos = hospitalService.GetAllHospitall();
            ViewBag.Hospitals = hos;

            //获取体检类型列表
            var combos = physicalService.GetAllComboType();
            ViewBag.Combos = combos;

            //获取体检项目列表
            var items = physicalService.GetAllPhysicalItem();
            ViewBag.Items = items;

            return View();
        }

        //删除套餐
        public ActionResult PhysicalDelete(int id)
        {
            var result = physicalService.DeletePhysicalById(id);
            if (result)
            {
                return Json(new { Code = 1, Msg = "处理成功！" });
            }
            else
            {
                return Json(new { Code = 0, Msg = "处理失败！" });
            }
        }
        [HttpPost]
        //添加套餐
        public JsonResult PhysicalAdd(string Name, int Hospital, int ComboTypeId, string Price, string Appropriate, string Details, int Items)
        {

            double Price_dou = 0;
            if(!string.IsNullOrEmpty(Price))
            {
                Price_dou = double.Parse(Price);
            }
            var result = false;
            result = physicalService.AddComboSingle(Name, Hospital, ComboTypeId, Price_dou, Appropriate, Details, Items);
            if (result)
            {
                return Json(new { Code = 1, Msg = "处理成功！" });
            }
            else
            {
                return Json(new { Code = 0, Msg = "处理失败！" });
            }
        }


        //添加体检套餐
        public ActionResult PhysicalComboAdd(string Name, int Hospital, int ComboTypeId, double Price, string Appropriate, string Details, List<int> Items)
        {
            var result = false;
            result = physicalService.AddCombo(Name,Hospital,ComboTypeId,Price,Appropriate,Details,Items);
            if (result)
            {
                return Json(new { Code = 1, Msg = "处理成功！" });
            }
            else
            {
                return Json(new { Code = 0, Msg = "处理失败！" });
            }
        }

        //编辑套餐
        public ActionResult EditComboSingle(int id, string name, int hospital, int comboTypeId, double price, string appropriate, string details, int items)
        {
            var result = false;
            var item=new List<int>();
            item.Add(items);
            result = physicalService.EditCombo(id,name, hospital, comboTypeId, price, appropriate, details,item);
            if (result)
            {
                return Json(new { Code = 1, Msg = "处理成功！" });
            }
            else
            {
                return Json(new { Code = 0, Msg = "处理失败！" });
            }
        }



        //编辑体检套餐
        public ActionResult EditCombo(int id, string name, int hospital, int comboTypeId, double price, string appropriate, string details, List<int> items)
        {
            var result = false;
            result = physicalService.EditCombo(id, name, hospital, comboTypeId, price, appropriate, details, items);
            if (result)
            {
                return Json(new { Code = 1, Msg = "处理成功！" });
            }
            else
            {
                return Json(new { Code = 0, Msg = "处理失败！" });
            }
        }

        public ActionResult GetCombo(int id)
        {
            Combo data=physicalService.GetCombo(id);
            if (null!=data)
            {
                return Json(new { Code = 1, Msg = "处理成功！", Data = data });
            }
            else
            {
                return Json(new { Code = 0, Msg = "处理失败！", Data = data });
            }
        }
        //public ActionResult Adduser()
        //{
        //    string name = Request["name"];
        //    string pwd = Request["Password"];

        //}        
        [HttpPost]
        public int Adduser()
        {
            int id = Convert.ToInt32(Request["id"]);
            string name = Request["name"];
            string pwd = Request["pwd"];
            if (hospitalAdminService.Adduser(id, name, pwd) == true)
            {
                return 1;
            }
            else
            {
                return 0;
            }
        }
        /// <summary>
        /// 返回信息导入视图
        /// </summary>
        /// <returns></returns>
        public ActionResult ImputFile()
        {

            return View(physicalService.ShowFile(null));
        }
        /// <summary>
        /// 上传文件
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ActionResult ImputFile(PhysicalItemFiles fiels,HttpPostedFileBase image)
        {
            //判断上传的文件是否存在
            if(image!=null)
            {
                //string filename = fiels.PhysicalItemFileName + image.FileName.Substring(image.FileName.LastIndexOf('.'));//获取要保存的文件名
                image.SaveAs(Server.MapPath("/Filestree/") + image.FileName);//获取文件的绝对路径
                fiels.PhysicalItemFileName = image.FileName;
                fiels.PhysicalItemFileUrl = "/Filestree/" + image.FileName;
                fiels.PhysicalItemType = int.Parse(Request.Form.Get("Stateid"));//获取上传文件的类型
                if (fiels.PhysicalItemType==2)
                {
                    return Content("<script>alert('请选择文件类型');location.href='/Admin/ImputFile'</script>");
                }
                else
                {
                    if (physicalService.AddPhysicitemFile(fiels))
                    {
                        return Content("<script>alert('文件" + image.FileName + "上传成功!');location.href='/Admin/ImputFile'</script>");
                    }

                    else
                    {
                        return Content("<script>alert('文件" + image.FileName + "上传失败!');location.href='/Admin/ImputFile'</script>");
                    }

                }

            }
            else
            {
                return Content("<script>alert('请选择上传的文件');location.href='/Admin/ImputFile'</script>");
            }
        }
        /// <summary>
        /// 体检项信息数据导入
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ActionResult InsertFile(string id)
        {
            try
            {
                List<PhysicalItemFiles> itemfile = physicalService.ShowFile(id);//根据要导入的数据查找对应的文件
                bool flag = false;
                //0代表体检项目,1代表套餐
                if (itemfile[0].PhysicalItemType == 0)
                {
                    DataTable table = this.ImportExcelFile(@Url.Content(itemfile[0].PhysicalItemFileUrl));
                    //循环添加体检项数据
                    for (int i = 0; i < table.Rows.Count; i++)
                    {
                        string name = table.Rows[i][0].ToString();//获取体检项目名称

                        string puponse = table.Rows[i][1].ToString();//获取体检项描述

                        float price = float.Parse(table.Rows[i][2].ToString());//获取体检项价格

                        string PhysicalItemType = table.Rows[i][3].ToString().Trim();//获取体检项类型

                        int typeiid = physicalService.ShowTypeid(PhysicalItemType);

                        int hospitalid = physicalService.ShowHospitalId(table.Rows[i][4].ToString());//获取医院编号

                        if (physicalService.InsertPhysical(name, puponse, price, hospitalid, typeiid))
                        {

                            flag = true;
                        }
                        else
                        {
                            flag = false;
                        }

                    }
                    if (flag == true)
                    {
                        if (physicalService.DeletePhysical(int.Parse(id)))
                        {
                            return Content("<script>alert('体检项目文件导入成功');location.href='/Admin/ImputFile'</script>");
                        }
                        else
                        {
                            return Content("<script>alert('体检项目文件导入失败');location.href='/Admin/ImputFile'</script>");
                        }
                    }
                    else
                    {
                        return Content("<script>alert('体检项目文件导入失败');location.href='/Admin/ImputFile'</script>");
                    }
                }
                else
                {
                    DataTable table = this.ImportExcelFile(@Url.Content(itemfile[0].PhysicalItemFileUrl));

                    Combo comb = new Combo();//实例化套餐对象
                    List<int> combid = new List<int>();
                    //循环添加套餐数据
                    for (int i = 0; i < table.Rows.Count; i++)
                    {
                        comb.Price = Convert.ToDecimal(table.Rows[i][0].ToString());//获取套餐价格
                        decimal OriginalPrice = Convert.ToDecimal(table.Rows[i][1].ToString());//获取优惠价格
                        comb.Name = table.Rows[i][2].ToString();//获取套餐名
                        comb.Details = table.Rows[i][3].ToString();//套餐介绍
                        comb.HospitalId = physicalService.ShowHospitalId(table.Rows[i][4].ToString());//获取医院ID
                        comb.Appropriate = table.Rows[i][5].ToString();//适宜人群
                        comb.ComboTypeId = physicalService.Comtypid(table.Rows[i][6].ToString());//套餐类型
                        comb.Oldprice = Convert.ToDecimal(table.Rows[i][7].ToString());//套餐源价格
                        comb.Sonnum = 0;//预约人数
                        comb.Scheck = table.Rows[i][8].ToString();//重点检查项目
                        if (physicalService.AddComboItem(comb, OriginalPrice))
                        {
                            //以下方法同步套餐和体检项数据表t_combotophysicalitem

                            List<string> prolist = physicalService.ShowComtable();//获取套餐ID和体检项目信息
                            combid.Clear();
                            string[] regsult = prolist[1].Split('、');//分割体检项目,以便查询对应的项目编号
                            //如果套餐和体检项关系表中不存再此套餐信息则进行添加
                            if (physicalService.ShowComPrhyItem(int.Parse(prolist[0])).Rows.Count<=0)
                            {
                                foreach (var item in regsult)
                                {
                                   combid.Add(physicalService.Showphysicalitemdto(item));//获取体检项目编号,并添加到集合中
                                }
                                //循环添加t_combotophysicalitem表的套餐ID和项目ID
                                for(int com=0;com<combid.Count;com++)
                                {
                                    if(physicalService.Addt_combotophysicalitem(int.Parse(prolist[0]), int.Parse(combid[com].ToString())))
                                    {
                                        flag = true;
                                    }
                                    else
                                    {
                                        flag = false;//如果一次失败则结束循环,代表同步套餐和体检项目表t_combotophysicalitem失败
                                        break;
                                    }
                                }

                            }


                            //flag = true;
                        }
                        else
                        {
                            flag = false;
                        }

                    }
                    if (flag == true)
                    {
                        if (physicalService.DeletePhysical(int.Parse(id)))
                        {
                            return Content("<script>alert('套餐文件导入成功');location.href='/Admin/ImputFile'</script>");
                        }
                        else
                        {
                            return Content("<script>alert('套餐文件导入失败');location.href='/Admin/ImputFile'</script>");
                        }
                    }
                    else
                    {
                        return Content("<script>alert('套餐文件导入失败');location.href='/Admin/ImputFile'</script>");
                    }
                }
            }
            catch (Exception ex)
            {
                return Content("<script>alert('文件导入失败');location.href='/Admin/ImputFile'</script>");
            }


              
        }
        /// <summary>
        /// 根据excel列的类型获取列的值
        /// </summary>
        /// <returns></returns>
        private static string GetCellValue(ICell cell)
        {
            if (cell == null)
                return string.Empty;
            switch (cell.CellType)
            {
                case CellType.Blank:
                    return string.Empty;
                case CellType.Boolean:
                    return cell.BooleanCellValue.ToString();
                case CellType.Error:
                    return cell.ErrorCellValue.ToString();
                case CellType.Numeric:
                case CellType.Unknown:
                default:
                    return cell.ToString();//This is a trick to get the correct value of the cell. NumericCellValue will return a numeric value no matter the cell value is a date or a number
                case CellType.String:
                    return cell.StringCellValue;
                case CellType.Formula:
                    try
                    {
                        HSSFFormulaEvaluator e = new HSSFFormulaEvaluator(cell.Sheet.Workbook);
                        e.EvaluateInCell(cell);
                        return cell.ToString();
                    }
                    catch
                    {
                        return cell.NumericCellValue.ToString();
                    }
            }
        }
        /// <summary>
        /// 导入数据
        /// </summary>
        /// <param name="filePath"></param>
        /// <returns></returns>
        public DataTable ImportExcelFile(string filePath)
        {
            HSSFWorkbook hssfworkbook;
            #region//初始化信息
            try
            {
                using (FileStream file = new FileStream(filePath, FileMode.Open, FileAccess.Read))
                {
                    hssfworkbook = new HSSFWorkbook(file);
                }
            }
            catch (Exception e)
            {
                throw e;
            }
            #endregion
           
            //for (int sheet1 = 0; sheet1 < hssfworkbook.NumberOfSheets; sheet1++)
            //{
                NPOI.SS.UserModel.ISheet sheet = hssfworkbook.GetSheetAt(0);

                DataTable table = new DataTable();
                IRow headerRow = sheet.GetRow(0);//第一行为标题行
                int cellCount = headerRow.LastCellNum;//LastCellNum = PhysicalNumberOfCells
                int rowCount = sheet.LastRowNum;//LastRowNum = PhysicalNumberOfRows - 1

                //handling header.
                for (int i = headerRow.FirstCellNum; i < cellCount; i++)
                {
                    DataColumn column = new DataColumn(headerRow.GetCell(i).StringCellValue);
                    table.Columns.Add(column);
                }
                for (int i = (sheet.FirstRowNum + 1); i <= rowCount; i++)
                {
                    IRow row = sheet.GetRow(i);
                    DataRow dataRow = table.NewRow();

                    if (row != null)
                    {
                        for (int j = row.FirstCellNum; j < cellCount; j++)
                        {
                            if (row.GetCell(j) != null)
                                dataRow[j] = GetCellValue(row.GetCell(j));
                        }
                    }

                    table.Rows.Add(dataRow);
                }



            //}


            return table;
        }

        #endregion

        #region 系统管理

        public ActionResult City()
        {
            return View();
        }

        public ActionResult Region()
        {
            return View();
        }

        #endregion

    }
}